import axios from "axios";
import { closeToast, showLoadingToast, showToast } from "vant";
import router from "@/router/index";

const instence = axios.create({
  baseURL: import.meta.env.VITE_BASE_URL,
});

instence.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem("token");
    if (token) {
      config.headers.Authorization = `${token}`;
    }

    showLoadingToast({
      message: "加载中...",
      forbidClick: true,
    });
    return config;
  },

  (error) => {
    closeToast();
    Promise.reject(error);
  }
);

instence.interceptors.response.use(
  (response) => {
    closeToast();
    return response;
  },
  (error) => {
    closeToast();
    console.log(error.response);
    if (error.response.status == 401) {
      console.log("未登录");
      router.push("/login");
    }
    showToast({ message: error.response.data.message });

    return Promise.reject(error);
  }
);

export default instence;
